<template>
  <div class="weather-content" ref="echartRef"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";

import { getWeatherForecast, getCityLookup } from "@/utils/shuiwu/api";

const tem1 = ref<number[]>([]); //最高温度
const tem2 = ref<number[]>([]); //最低温度
const weatherDay = ref<string[]>([]);
const weaterImg = ref<string[]>([]);
const weaterDesc = ref<string[]>([]);

async function initChart() {
  await fetch(
    "https://nx3qqpjfx5.re.qweatherapi.com/v7/weather/7d?location=101170101",
    {
      headers: {
        "X-QW-Api-Key": "efc5709adc0a453793cdabf5b94245fb",
      },
    }
  )
    .then((r) => {
      if (r.status == 200) {
        return r.json();
      } else {
        return Promise.reject(r.json());
      }
    })
    .then((res) => {
      res.daily.forEach((element, i) => {
        // 最高温度
        tem1.value.push(element.tempMax);
        // 最低温度
        tem2.value.push(element.tempMin);
        // 天气图片
        weaterImg.value.push(element.iconDay);
        // 天气描述
        weaterDesc.value.push(element.textDay);
      });
    });
}

/**
 * 获取城市ID
 */
// async function cityLookup() {
// await getCityLookup().then(data => {
// })
// }
// cityLookup()

const echartRef = ref(null);
let chartInstance = null;

// 监听 ScalablePage 缩放的 scale 变化
const props = defineProps({
  scale: {
    type: Number,
    default: 1,
  },
});

/**
 * 获取今天是周几
 */
const dayIsToday = () => {
  const Today = new Date().getDay();
  const WEEKDAY = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  WEEKDAY.forEach((_, i) => {
    weatherDay.value.push(i == 0 ? "今天" : WEEKDAY[(Today + i) % 7]);
  });
};
dayIsToday();

/**
 * 彩云api
 */
async function getWeather() {
  await getWeatherForecast().then((data) => {});
}

function initEchart() {
  chartInstance = echarts.init(echartRef.value, null, {
    devicePixelRatio: window.devicePixelRatio * props.scale || 1,
  });

  let options = {
    grid: {
      show: false,
      backgroundColor: "transparent",
      opacity: 0.3,
      borderWidth: "0",
      top: "70",
      bottom: "20",
    },
    tooltip: { trigger: "axis" },
    legend: { show: false },
    xAxis: [
      /**
       * 周 样式
       */
      {
        type: "category",
        boundaryGap: false,
        position: "top",
        offset: 50,
        zlevel: 50,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          formatter: ["{a|{value}}"].join("\n"),
          rich: {
            a: {
              color: "white",
              // fontFamily: "Alibaba PuHuiTi 2-75 SemiBold",
              fontSize: 8,
            },
          },
        },
        data: weatherDay.value,
      },
      // 图标 阴晴 样式
      {
        type: "category",
        boundaryGap: false,
        position: "top",
        offset: 10,
        zlevel: 100,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          formatter: function (value: any, index: any) {
            return "{" + index + "| }\n{b|" + value + "}";
          },
          rich: {
            // 图标样式
            ...weaterImg.value.reduce(
              (obj: any, image: string, index: number) => {
                obj[index] = {
                  backgroundColor: { image: `/icons/${image}-fill.svg`,},
                  height: 15,
                  width: 15,
              };
              return obj;
            },
            {}
          ),
          // 天气状况 样式
          b: {
              color: "#fff",
              fontSize: 8,
              lineHeight: 20,
              height: 40,
            },
          },
        },
        data: weaterDesc.value,
      },
    ],
    yAxis: {
      type: "value",
      show: false,
      axisLabel: {
        formatter: "{value}°C",
        color: "white",
      },
    },
    series: [
      /**
       * 最高气温折线图
       */
      {
        name: "最高气温",
        type: "line",
        data: tem1.value,
        symbol: "circle",
        smooth: true,
        itemStyle: { color: "#fff" },
        label: {
          show: true,
          position: "top",
          color: "white",
          formatter: "{c}°C",
          fontSize: 8,
        },
        lineStyle: { color: "#e18803" },
      },
      /**
       * 最低气温折线图
       */
      {
        name: "最低气温",
        type: "line",
        data: tem2.value,
        symbol: "circle",
        smooth: true,
        itemStyle: { color: "#fff" },
        label: {
          show: true,
          position: "bottom",
          color: "white",
          formatter: "{c}°C",
          fontSize: 8,
        },
        lineStyle: { color: "#144493" },
      },
    ],
  };
  chartInstance.setOption(options);
}
watch(
  () => props.scale,
  (newScale) => {
    if (chartInstance) {
      nextTick(() => {
        chartInstance.dispose();
        initChart();
      });
    }
  }
);

onMounted(async () => {
  await initChart();
  await initEchart();
});

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
</script>

<style scoped>
.weather-content {
  width: 240px;
  height: 120px;
}
</style>